package io.cici.server.core.handler;

import io.cici.common.RemoteConstant;
import io.cici.common.enums.TaskInstanceStatus;
import io.cici.common.request.TaskTrackerReportInstanceStatusRequest;
import io.cici.common.request.WorkerHeartbeatRequest;
import io.cici.common.response.AskResponse;
import io.cici.remote.framework.actor.Actor;
import io.cici.server.core.instance.TaskInstanceManager;
import io.cici.server.monitor.MonitorService;
import io.cici.server.monitor.events.w2s.TtReportInstanceStatusEvent;
import io.cici.server.monitor.events.w2s.WorkerHeartbeatEvent;
import io.cici.server.persistence.remote.repository.ContainerInfoRepository;
import io.cici.server.remote.worker.AppWorkerStatusManagerService;
import io.cici.server.remote.worker.WorkerClusterQueryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

/**
 * receive and process worker's request
 */
@Slf4j
@Component
@Actor(path = RemoteConstant.S4W_PATH)
public class WorkerRequestHandlerImpl extends AbWorkerRequestHandler {

    private final TaskInstanceManager taskInstanceManager;


    public WorkerRequestHandlerImpl(TaskInstanceManager taskInstanceManager,
                                    MonitorService monitorService, Environment environment, ContainerInfoRepository containerInfoRepository, WorkerClusterQueryService workerClusterQueryService) {
        super(monitorService, environment, containerInfoRepository, workerClusterQueryService);
        this.taskInstanceManager = taskInstanceManager;


    }

    @Override
    protected void processWorkerHeartbeat0(WorkerHeartbeatRequest heartbeat, WorkerHeartbeatEvent event) {
        AppWorkerStatusManagerService.updateStatus(heartbeat);
    }

    @Override
    protected AskResponse processTaskTrackerReportInstanceStatus0(TaskTrackerReportInstanceStatusRequest req, TtReportInstanceStatusEvent event) throws Exception {


        taskInstanceManager.updateStatus(req);

        // 结束状态（成功/失败）需要回复消息
        if (TaskInstanceStatus.FINISHED_STATUS.contains(req.getInstanceStatus())) {
            return AskResponse.succeed(null);
        }

        return null;
    }


}
